//createWebHistory路由模式路径不带#号(生产环境下不能直接访问项目，需要nginx转发)
//createWebHashHistory路由模式路径带#号
import { createRouter, createWebHistory, createWebHashHistory } from "vue-router";
import utils from "assets/js/utils.js";
import { ElMessage } from "element-plus";

const Login = () => import("views/login/Login.vue");
const Home = () => import("views/home/Home.vue");
const Welcome = () => import("views/home/Welcome.vue");
const User = () => import("views/user/User.vue");
const Role = () => import("views/role/Role.vue");
const Permission = () => import("views/power/Permission.vue");

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/home",
    component: Home,
    redirect: "/welcome",
    children: [
      {
        path: "/welcome",
        component: Welcome,
      },
      {
        path: "/users",
        component: User,
      },
      {
        path: "/roles",
        component: Role,
      },
      {
        path: "/permissions",
        component: Permission,
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //to 将要访问的路径
  //from 代表从哪个路径跳转而来
  //next 是一个函数,表示放行
  //  next() 放行, next('/login') 强制跳转
  if (to.path === "/login") return next();
  //跳转页面时,刷新token的刷新时间
  utils.saveRefreshTime();
  //获取token
  const token = JSON.parse(window.sessionStorage.getItem("token"))?.token;
  //没有token,跳转回登录页
  if (!token) {
    // if (from.path === "/login") {
    ElMessage.error({
      showClose: true,
      message: "登录状态过期,请重新登录",
    });
    // }
    // return next(`/login?redirect=${to.path}`);
    return next("/login");
  }
  next();
});

export default router;
